package com.hschinese.pronunciation.widget;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.PlayAssetData;
import com.hschinese.pronunciation.interfaces.IseScoreInterface;
import com.hschinese.pronunciation.interfaces.PlayClickListener;
import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.interfaces.RecognizeFinishListener;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.iseutil.IseUtil;
import com.hschinese.pronunciation.utils.HsSoundUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.UIUtils;
import com.hschinese.pronunciation.utils.Utils;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import static com.hschinese.pronunciation.R.id.play_control_record;

/**
 * Created by wo on 2015/11/2.
 */
public class PlayControlView extends LinearLayout implements View.OnClickListener{
    private Context mContext = null;
    private ImageView mPlayStandard, mRecord, mPlayRecord;
    private View mView = null;
    private RoundProgressBar mPlayOrgBar, mPlayRecordBar;

    private String mStandardUrl = null;
    private String mRecordUrl = null;
    private boolean useScore = false;
    private String chineseStr = "";
    private boolean isPlaying = false;
    private PlayClickListener mListener;
    private VolumeListener mVolumeListener;
    private RecordStatusListener mRecordListener;
    private PlayAssetData mPrePlayData = null;
    private long recordStartTime = 0L;

    private boolean useKdxfRecord = false;
    private HsDialog mRecognizeDialog = null;
    private RecognizeFinishListener mRecognizeListener = null;
    private boolean mPlayOrgFlag = false;
    private boolean mPlayRecordFlag = false;

    private Handler mHandler;


    public PlayControlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mView = LayoutInflater.from(context).inflate(R.layout.play_control_view, null);
        mPlayStandard = (ImageView)mView.findViewById(R.id.play_control_standard);
        mRecord = (ImageView)mView.findViewById(play_control_record);
        mPlayRecord = (ImageView)mView.findViewById(R.id.play_control_play);
        mPlayOrgBar = (RoundProgressBar)mView.findViewById(R.id.play_control_org_bar);
        mPlayRecordBar = (RoundProgressBar)mView.findViewById(R.id.play_control_record_bar);
        mRecognizeDialog = new HsDialog(mContext, R.style.pop_dialog, getResources().getString(R.string.recognizing), true, false);
        mRecognizeListener = new RecognizeFinishListener() {
            @Override
            public void onRecognizeFinish() {
                if (mRecognizeDialog != null && mRecognizeDialog.isShowing()) {
                    mRecognizeDialog.dismiss();
                    timer(500, 100);
                }
            }
        };

        mPlayStandard.setOnClickListener(this);
        mPlayRecord.setOnClickListener(this);
        mRecord.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {


                record(event);
                return true;
            }
        });
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 100) {
                    stop();
                } else if (msg.what == 101) {
                    if (useKdxfRecord) {
                        mRecordUrl = IseUtil.ISE_RECORD_PATH;
                    } else {
                        mRecordUrl = SimpleRecordUtil.recPath;
                    }
                    Logger.e("xionghy - PlayControlView - useScore: " + useScore + " -- " + mRecordUrl);
                    File f = new File(mRecordUrl);
                    if (f.exists()) {
                        isPlaying = true;
                        mPlayRecordFlag = true;
                        mPlayRecord.setImageResource(R.drawable.ic_playing);
                        SimpleRecordUtil.getInstance(mContext).setPlayCompleteListener(new PlayCompleteListener() {
                            @Override
                            public void playComplete() {
                                isPlaying = false;
                                mPlayRecord.setImageResource(R.drawable.ic_play);
                            }
                        });


                        int duration = SimpleRecordUtil.getInstance(mContext).playMicFile(f);
                        playStandardProgress(duration);
                    }
                }
            }
        };
        this.addView(mView);
    }

    public void resetAll() {
        resetProgressBar();
        resetPlayRecordProgress();
    }

    public void resetProgressBar() {
        if (mPlayOrgBar != null) {
            mPlayOrgFlag = true;
        }
    }

    public void resetPlayRecordProgress() {
        if (mPlayRecordBar != null) {
            mPlayRecordFlag = false;
        }
        mPlayRecord.setImageResource(R.drawable.ic_play);
    }
    public void playanimi(ImageView imageView) {
        imageView.setImageResource(R.drawable.voice_animator_lu);
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        animationDrawable.start();
    }
    public void stopAnimi(ImageView imageView) {
        imageView.setImageResource(R.drawable.voice_animator_lu);
        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
        animationDrawable.stop();
    }

    public void setPlayRecordVisibility(int id) {
        mPlayRecord.setVisibility(id);
        mPlayRecordBar.setVisibility(id);
    }

    public void setRecordVisibility(int id) {
        mRecord.setVisibility(id);
    }

    public void setStandardUrl(String url) {
        mStandardUrl = url;
    }

    public void setRecordUrl (String url) { mRecordUrl = url; }

    public void isUseScore(boolean b) {  useScore = b; }

    public void setChineseStr(String s) { chineseStr = s; }

    public void setScoreListener(IseScoreInterface listener) { IseUtil.getInstance(mContext).setListener(listener);  }

    public void setPlayClickListener(PlayClickListener l) { mListener = l; }

    public void setRecordListener(RecordStatusListener l) { mRecordListener = l; }

    public void setVolumeListener(VolumeListener l) { mVolumeListener = l; }

    private void record(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if(mPrePlayData!=null){
                    mPrePlayData.stopPlay();
                }
                resetProgressBar();
                SimpleRecordUtil.getInstance(mContext).stopPlayer();
                resetPlayRecordProgress();
                startRecord();
                break;
            case MotionEvent.ACTION_UP:
                stopRecord();
                if (useKdxfRecord) {
                    IseUtil.getInstance(mContext).stopRecord();
                    // TODO 添加识别等待
                    mRecognizeDialog.show();
                } else {
                    timer(500, 100);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 要区分成是否需要由科大讯飞来打分
     */
    private boolean startRecord() {
        mRecord.setImageResource(R.drawable.ic_speaker_focus);
        mRecordListener.startRecord();
        recordStartTime = System.currentTimeMillis();
        if (useScore) {
            if (!Utils.isNetworkValid(mContext)) {
                useKdxfRecord = false;
                SimpleRecordUtil.getInstance(mContext).setVolumeListener(mVolumeListener);
                SimpleRecordUtil.getInstance(mContext).startRecorder();
                UIUtils.showToast(mContext, getResources().getString(R.string.network_unavalible), Toast.LENGTH_SHORT);
                return false;
            }
            try {
                useKdxfRecord = true;
                IseUtil.getInstance(mContext).setVolumeListener(mVolumeListener);
                IseUtil.getInstance(mContext).startRecord(chineseStr);
                IseUtil.getInstance(mContext).setRecognizeListener(mRecognizeListener);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } else { // 纯粹的录制
            SimpleRecordUtil.getInstance(mContext).setVolumeListener(mVolumeListener);
            boolean b = SimpleRecordUtil.getInstance(mContext).startRecorder();
            return b;
        }
        return true;
    }

    private void stopRecord() {
        mRecord.setImageResource(R.drawable.ic_speaker_unfocus);
        mRecordListener.stopRecord();
    }

    private void stop() {
        if (useScore) {
            stopRecord();
            SimpleRecordUtil.getInstance(mContext).stopRecorder();
            IseUtil.getInstance(mContext).stopRecord();
            setPlayRecordVisibility(View.VISIBLE);
            playStandard();
            timer(2000, 101);
        } else {
            SimpleRecordUtil.getInstance(mContext).stopRecorder();
            long time = System.currentTimeMillis() - recordStartTime;
            if (time < 500) {
                UIUtils.showToast(mContext, getResources().getString(R.string.err_10118), Toast.LENGTH_SHORT);
                File f = new File(SimpleRecordUtil.recPath);
                if (f.exists()) {
                    f.delete();
                }
                return;
            }
            File f = new File(SimpleRecordUtil.recPath);
            if (f.exists()) {
                setPlayRecordVisibility(View.VISIBLE);
                // TODO 播放
                Logger.e("xionghy --- auto play standard.");
                playStandard();
                timer(2000, 101);
            }
        }
    }

    /**
     * 释放资源，做数据清理，在Activity中的onDestory中使用
     */
    public void destory() {
        if (useScore) {
            IseUtil.getInstance(mContext).destory();
        } else {
            SimpleRecordUtil.getInstance(mContext).stopRecorder();
        }
        SimpleRecordUtil.getInstance(mContext).stopPlayer();
    }

    public void playStandard() {
        if (mStandardUrl != null && !TextUtils.isEmpty(mStandardUrl)) {
            if (mPrePlayData != null) {
                mPrePlayData.stopPlay();
            }
            mPrePlayData = HsSoundUtil.playAsset(mContext, mStandardUrl);
//            Logger.e("xionghy - duration: " + mPrePlayData.getDuration());
            mPlayOrgFlag = false;
            play();
        } else {
            Logger.e("Org data was not exist!");
        }
    }

    private void startTask(float t, final AnimationDrawable draw) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.stop();
            }
        }, (int) (t * 1000));
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.play_control_standard) {
            playStandard();
            if (mListener != null) {
                mListener.onPlayClicked(isPlaying);
            }
        } else if (id == R.id.play_control_play) {
            if (useKdxfRecord) {
                mRecordUrl = IseUtil.ISE_RECORD_PATH;
            } else {
                mRecordUrl = SimpleRecordUtil.recPath;
            }
            Logger.e("xionghy - PlayControlView - useScore: " + useScore + " -- " + mRecordUrl);
            File f = new File(mRecordUrl);
            if (f.exists()) {
                isPlaying = true;
                mPlayRecordFlag = true;
                mPlayRecord.setImageResource(R.drawable.ic_playing);
                SimpleRecordUtil.getInstance(mContext).setPlayCompleteListener(new PlayCompleteListener() {
                    @Override
                    public void playComplete() {
                        isPlaying = false;
                        mPlayRecord.setImageResource(R.drawable.ic_play);
                    }
                });
                int duration = SimpleRecordUtil.getInstance(mContext).playMicFile(f);
                playStandardProgress(duration);
            }
        }
    }

    private void play() {
        mPlayStandard.setImageResource(R.drawable.voice_animator);
        AnimationDrawable draw = (AnimationDrawable) mPlayStandard.getDrawable();
        draw.setOneShot(true);
        draw.start();
        startTask(1.5f, draw);
        updateProgress(1200);
    }

    int progress = 0;
    private void updateProgress(int time) {
        progress = 0;
        mPlayOrgBar.setProgress(progress);
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(progress <= 100){
                    if (mPlayOrgFlag) break;
                    progress += 5;
                    mPlayOrgBar.setProgress(progress);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                mPlayOrgFlag = false;
                progress = 0;
                mPlayOrgBar.setProgress(progress);
            }
        }).start();
    }

    private int standardProgress = 0;
    private void playStandardProgress(final int duration) {
        mPlayRecordBar.setMax(duration);
        mPlayRecordBar.setProgress(standardProgress);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progressSteps = duration / 100;
                while(standardProgress <= duration){
                    if (!mPlayRecordFlag) break;
                    standardProgress += progressSteps;
                    mPlayRecordBar.setProgress(standardProgress);
                    try {
                        Thread.sleep(progressSteps);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                standardProgress = 0;
                mPlayRecordBar.setProgress(standardProgress);
            }
        }).start();
    }

    private void timer(int delay, final int what) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(what);
                    this.cancel();
                    timer.cancel();
                }
            }
        }, delay);
    }
    private static final int MESSAGE_LOGIN = 1;
    Handler  handler = new Handler(new Handler.Callback(){
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what == MESSAGE_LOGIN ){
                //登录逻辑

            }
            return true;
        }
    });
    //五秒后发送

    public void setPlayanim(boolean b) {
        AlphaAnimation alphaAnimation = (AlphaAnimation) AnimationUtils.loadAnimation(mContext, R.anim.play_animator);
        if(b){

            mPlayStandard.startAnimation(alphaAnimation);
        }else {
            alphaAnimation.cancel();
        }

    }
    public void setVoanim(boolean b) {
        AlphaAnimation alphaAnimation = (AlphaAnimation) AnimationUtils.loadAnimation(mContext, R.anim.play_animator);
        if(b){

            mRecord.startAnimation(alphaAnimation);
        }else {
            alphaAnimation.cancel();
        }

    }
    private void startTask1(float t, final AlphaAnimation draw) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.cancel();
            }
        }, (int) (t * 1000));
    }
}
